<?php
	$airmonths = array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	$oldmovie = "";
	$olddir = "";
	$tvxml = "";
	$imdbnr = 0;
	$movtypes = array("mov","avi","mpg","mpeg","divx","ogm","mkv","mp4","m4v","mp4v");


	if(isset($argv[1]) and file_exists($argv[1]) and is_dir($argv[1])){
//		$output = fopen("/tmp/series.tmp","w");
		processdirectory($argv[1]);
//		fclose($output);
	}else{
		die("\nUsage: php series_prepare.php <directory>\n\n");
	}



	function processdirectory($dir){
		global $airmonths, $oldmovie, $movtypes, $tvxml, $olddir, $imdbnr, $argv; // $output
	
		$d = opendir($dir);
		while(false !== ($file = readdir($d))){
			if(substr($file, 0, 1) == "."){ continue; }
			if(is_dir($dir.$file."/")){
				processdirectory($dir.$file."/");
				continue;
			}
			$ext = strtolower(substr($file, strrpos($file, ".")+1));
			if(!in_array($ext, $movtypes)){ continue; }
//			echo "Processing file ".$file."\n";

			$matches = array();
			if(preg_match("/(.+?)\Ds(\d+)\.?e(\d+?)\D/i", $file, $matches)){
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\Ds(\d+)\.?x(\d+?)\D/i", $file, $matches)){
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)x(\d+)\D/i", $file, $matches)){
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)\D/", $file, $matches)){
				$episode = round(substr($matches[2],1));
				$season  = round(substr($matches[2],0,1));
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(\d+?) - ([\w\s]+) - /", $file, $matches)){
				$episode = round(substr($matches[1],1));
				$season  = 1;
				$title   = str_replace("."," ",$matches[2]);
			}

/*
			$temp = get_show($title,0, $season."x".$episode);

			$title = substr($temp[5],strpos($temp[5], "\"")+1);
			$title = substr($title, 0, strpos($title, "\""));
			
			$movie = '"'.trim($temp[0]).'"';
*/
			echo("$dir$file\t$file\t$season\t$episode\t");
			// XML
			if(!file_exists($dir.str_replace(".".$ext,".xml", $file))){
				echo("3\t");
			}else{
				echo("1\t");
			}
			// subtitles
			if((!file_exists($dir.str_replace(".".$ext,".srt", $file))) and (!file_exists($dir.str_replace(".".$ext,".sub", $file)))){
				echo("3\t");
			}else{
				echo("1\t");
			}
			// screenshot
			if((!file_exists($dir.str_replace(".".$ext,".jpg", $file))) and (!file_exists($dir.str_replace(".".$ext,".png", $file)))){
				echo("3\t");
			}else{
				echo("1\t");
			}
			// Cover
			if(!file_exists($dir."cover.jpg")){
				echo("3\t");
			}else{
				echo("1\t");
			}
			echo("\n");
		}
	}

?>